import CryptoJS from 'crypto-js'

const socketService = {
  socket: null,
  heartbeatInterval:null,
  data:"",
  init() {
    console.log("websocket")
    if (typeof WebSocket === "undefined") {
      alert("您的浏览器不支持socket");
    } else {
      const apiKey = "d2a796c47f9322a548b68a6aef3f0faf";
      const apiSecret = "NzJmMDM2NmViZTU5NWNmN2ZjOGEwMzhk";
      let url = 'wss://spark-api.xf-yun.com/v3.1/chat';
      var host = location.host
      var date = new Date().toGMTString()
      var algorithm = 'hmac-sha256'
      var headers = 'host date request-line'
      var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v3.1/chat HTTP/1.1`

      var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
      var signature = CryptoJS.enc.Base64.stringify(signatureSha)
      var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
      var authorization = btoa(authorizationOrigin)
      url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
      let path = url; // 请求路径
      this.socket = new WebSocket(path);
      this.socket.onopen = this.open.bind(this);
      this.socket.onerror = this.error.bind(this);
      this.socket.onmessage = this.getMessage.bind(this);
    }
  },

  open() {
    console.log("socket连接成功");
    // this.startHeartbeat()
    // this.send("")
  },

  error() {
    console.log("连接错误");
  },
  //这里我判断了 是不是  JSON  （要和后端定一下结构类型） (二选一)
  getMessage() {
    this.socket.onmessage = (msg) => {
      console.log(msg.data)
      const result = JSON.parse(msg.data);
      console.log(result.payload.choices.text[0].content);
      this.data=this.data+result.payload.choices.text[0].content;
      alert(this.data)
    }

    // return new Promise((resolve, reject) => {
    //   this.socket.onmessage = (msg) => {
    //     console.log(msg)
    //     const result = JSON.parse(msg.data);
    //     console.log(result.payload.choices.text[0].content);
    //     this.data=this.data+result.payload.choices.text[0].content
    //     if(result.header.code==0){
    //       resolve(result.payload.choices.text[0].content)
    //     }
    //     // 利用promise 返回出去结果
    //     // if (msg.data !== '连接成功' && JSON.parse(msg.data)) {
    //     //   const data = JSON.parse(msg.data);
    //     //   resolve(data); // 将数据传递给调用者
    //     // }
    //
    //     // this.scrollInstance.refresh(); // 手动刷新滚动效果
    //
    //   };
    // });
    // this.scrollInstance.refresh(); // 手动刷新滚动效果
  },
  // 也可以这样写 end

  send(data) {
    if (this.socket) {
      this.data=""
      console.log("发送信息")
      var params= {
        "header": {
          "app_id": "00055ebc",
        },
        "parameter": {
          "chat": {
            "domain": "generalv3",
            "temperature": 0.5,
            "max_tokens": 1024
          }
        },
        "payload": {
          "message": {
            "text": [
            ]
          }
        }
      }
      params.payload.message.text.push({"role": "user", "content": data})
      this.socket.send(JSON.stringify(params));
    }
  },

  close() {
    console.log("socket已经关闭");
  },
  // startHeartbeat() {
  //   this.heartbeatInterval = setInterval(() => {
  //     if (this.socket && this.socket.readyState === WebSocket.OPEN) {
  //       this.socket.send(); // 发送心跳消息
  //     }
  //   }, 1000); // 每1秒发送一次心跳
  // },
};
//最后导出
export default socketService;
